package com.lvtu.monitor.quartz;

import com.lvmama.com.lvtu.common.utils.MemcachedUtil;
import com.lvtu.monitor.dao.config.MemConfig;
import com.lvtu.monitor.mongo.service.IBaseMongoService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 刷新memcached配置的失效时间
 * Created by lvzimin on 15/12/28.
 */
@Service
public class SwitchReloadJob implements ApplicationListener<ContextRefreshedEvent> {

    private final static Logger logger = Logger.getLogger(SwitchReloadJob.class);

    @Autowired
    IBaseMongoService mongoService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			// 需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
            ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
            // 每10s从mongodb中读取配置值,刷新到缓存中
            threadPool.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    List<MemConfig> memConfigs = mongoService.findAll(MemConfig.class);
                    for (MemConfig memConfig : memConfigs) {
                        if (!"true".equals(memConfig.getEnable())) {
                            continue;
                        }
                        String memKey = memConfig.getMemKey();
                        long mongoValue = memConfig.getValue();
                        long memValue = MemcachedUtil.getInstance().getCounter(memKey);
                        if (mongoValue != memValue) {
                            MemcachedUtil.getInstance().remove(memKey);
                            MemcachedUtil.getInstance().addOrIncrAndInit(memKey, mongoValue);
                            logger.info("config reloaded...memKey:" + memKey + ",memValue:" + memValue + ",mongoValue:" + mongoValue);
                        }
                    }
                }
            }, 1L, 10L, TimeUnit.SECONDS);
		}
    }

}
